package com.zhiwang.planet.mvvm.viewmodel.loginv2

import android.annotation.SuppressLint
import android.content.Context
import android.net.wifi.WifiManager
import android.os.Build
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.tencent.bugly.crashreport.CrashReport
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.aop.net.NetWorkRequired
import com.zhiwang.planet.aop.net.SimCardRequired
import com.zhiwang.planet.aop.sim.SimRequired
import com.zhiwang.planet.aop.util.Throttle
import com.zhiwang.planet.event.LoginEvent
import com.zhiwang.planet.mvvm.model.AppDataBase
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.request.LoginRequest
import com.zhiwang.planet.mvvm.model.request.SmsReq
import com.zhiwang.planet.ui.WebViewActivity
import com.zhiwang.planet.ui.loginv2.RegisterV2Activity
import com.zhiwang.planet.ui.loginv2.RegisterV2Step2Activity
import com.zhiwang.planet.ui.loginv2.WxLoginActivity
import com.zhiwang.planet.util.*
import com.zhiwang.planet.widget.ColdDownTextView
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import org.greenrobot.eventbus.EventBus


inline fun checkInput(text: String?, message: String? = ""): Boolean {

    return if (TextUtils.isEmpty(text)) {
        message?.apply { Toaster.message(this) }
        false
    } else true

}

class LoginViewModel : ViewModel() {


    lateinit var restApi: RestApi

    lateinit var context: AppCompatActivity

    var deviceId = ""


    val username = MutableLiveData<String>("")

    val smsCode = MutableLiveData<String>("")

    lateinit var errorHandler: (Throwable) -> Unit

    @SimCardRequired
    fun login() {

        val userName = username.value

        val sms = smsCode.value

        if (!checkInput(userName, "手机号不能为空")
                || !checkInput(sms, "验证码不能为空"))
            return

        val req = buildLoginReq()

        restApi.loginV2(req)
                .arrange(Consumer {
                    if (true) {
//                        TokenManager.saveToken(it.token)
                        EventBus.getDefault().post(LoginEvent())
//                        val userDao = AppDataBase.getInstance(context).userDao()
//                        userDao.addUser(it)
//                        CrashReport.setUserId(it.userId)
                        TokenManager.setPhoneLogged()
                        context.suicideAfterTransition()

                    } else {

                        //保存token,下个页面的请求头部带token
//                        TokenManager.saveToken(it.token)
                        context.quickStartActivity(WxLoginActivity::class.java) { intent ->
                            intent.apply {
                                putExtra("bindMode", true)
//                                putExtra("token", it.token)
                                putExtra("deviceId", deviceId)
                            }
                        }
                        context.suicideAfterTransition()
                    }

                }, {

                    errorHandler(it)
                })
    }

    private fun buildLoginReq(): LoginRequest {


        val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

        var wifiName = wifiManager.connectionInfo?.ssid ?: ""

        if (wifiName.indexOf("\"") == 0 && wifiName.lastIndexOf("\"") == wifiName.lastIndex)
            wifiName = wifiName.substring(1, wifiName.lastIndex)

        return LoginRequest(
                phone = username.value!!,
                sms = smsCode.value!!,
                imei = deviceId,
                get_token = 1,
                androidVersion = Build.VERSION.RELEASE,
                appVersionName = BuildConfig.VERSION_NAME,
                wifiName = wifiName,
                deviceModel = Build.MODEL)
    }


    fun service(){

        WebViewActivity.load(context,Store.Service)
    }

    @SimCardRequired
    fun wxAuth() {
        LoginUtil.wxLogin(context)
    }

    var receiveCode = false

    @SuppressLint("CheckResult")
    fun tryWxLogin(code: String) {


        val req = buildLoginReq()
        req.code = code

        restApi.wxLogin(req)
                .androidSchedule()
                .subscribe({

                    if (it.isOk()) {

                        AppUtil.handleLogin(it.data)
                        context.suicideAfterTransition()

                    } else if (it.errCode == 3) {


                        context.quickStartActivity(RegisterV2Activity::class.java) { intent ->
                            intent.apply {
                                putExtra("deviceId", deviceId)
                                //openid
                                putExtra("code", it.data)
                            }
                        }

                        context.suicideAfterTransition()


                    } else if (it.errCode == 2) {
                        context.quickStartActivity(RegisterV2Step2Activity::class.java) { intent ->
                            intent.apply {
                                putExtra("deviceId", deviceId)
                                //openid
                                putExtra("code", it.data)
                            }
                        }

                        context.suicideAfterTransition()

                    } else {
                        errorHandler(it.error())
                    }


                }, {
                    errorHandler(it)
                }, {

                })
    }


    fun getSmsCode(v: View) {

        val coldDownButton = v as ColdDownTextView

        val userName = username.value

        if (!checkInput(userName, "手机号不能为空"))
            return

        restApi.getSms(SmsReq(userName!!).apply { setTypeLogin() })
                .arrangeComplete(Action {
                    Toaster.message("验证码已发送")
                    coldDownButton.start()
                }, { errorHandler(it) })
    }

    fun register() {
        context.quickStartActivity(RegisterV2Activity::class.java) { intent ->
            intent.putExtra("deviceId", deviceId)
        }
        context.suicideAfterTransition()
    }


    val qq = MutableLiveData<String>()

    fun loadQQ() {

        restApi.getQQ()
                .arrange(Consumer {

                    qq.value = it.qq
                }, {

                })
    }


    fun copyQQ() {

        qq.value?.apply {
            context.copy(this)
            Toaster.message("已复制客服QQ到剪切板")
        }
    }


    fun  copyDeviceId(){
        deviceId.apply {
            context.copy(this)
            Toaster.message("已复制设备码到剪切板")
        }
    }
}